package me.pplay.playtalk.activity;

import java.io.IOException;
import java.util.Calendar;

import me.pplay.playtalk.ApplicationTrans;
import me.pplay.playtalk.R;
import me.pplay.playtalk.activity.setting.SettingLanguageActivity;
import me.pplay.playtalk.activity.setting.SettingNicknameActivity;
import me.pplay.playtalk.activity.setting.SettingSystemAvatarActivity;
import me.pplay.playtalk.callback.CropCallBack;
import me.pplay.playtalk.data.Globals;
import me.pplay.playtalk.net.SkyidOperation;
import me.pplay.playtalk.protocol.DataCallBack;
import me.pplay.playtalk.protocol.TpChat;
import me.pplay.playtalk.protocol.bean.RspData;
import me.pplay.playtalk.protocol.bean.TPBuddyinfo;
import me.pplay.playtalk.util.BuddyInfoUtil;
import me.pplay.playtalk.util.ImageCrop;
import me.pplay.playtalk.util.LogManager;
import me.pplay.playtalk.util.SkyUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ContactDetailsAboutActivity extends BaseActivity implements OnClickListener{
	private ImageButton btn_chat, btn_sms, btn_addfrd, btn_call,btn_systemavatar,btn_camera;
	private TextView title1, title2, title4, title5, title6, title7, title8,nickname_tv,pin_tv,title_tv;
	private RelativeLayout nickname_layout,email_layout,mobile_layout,birth_layout,gender_layout,country_layout,lan_layout;
	private Toast toast;
	
	private int skyid;
	private TPBuddyinfo buddyinfo;
	private TpChat tpChat;
	private ImageCrop imageCrop;
	private ImageView icon_iv;
	
	
	Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case TpChat.CHAT_GETINFO_TIMEOUT:
				showToast(getString(R.string.net_timeout));
				break;
			case TpChat.CHAT_GETINFO_OK:
				if(buddyinfo == null) return;
				setValues();
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_contactdetails_about);
		super.SetOnBackClickListener((ImageButton)findViewById(R.id.btn_back));
		findViews();
		initDatas();
		clickEvents();
	}
	
	private void findViews(){
		btn_chat	= (ImageButton)findViewById(R.id.detail_btn_chat);
		btn_sms	= (ImageButton)findViewById(R.id.btn_sms);
		btn_addfrd	= (ImageButton)findViewById(R.id.detail_btn_addfrd);
		btn_call	= (ImageButton)findViewById(R.id.btn_call);
		btn_systemavatar = (ImageButton)findViewById(R.id.detail_systemavatar);
		btn_camera = (ImageButton)findViewById(R.id.btn_camera);
		title1		= (TextView)findViewById(R.id.title1);
		title2		= (TextView)findViewById(R.id.title2);
		title4		= (TextView)findViewById(R.id.title4);
		title5		= (TextView)findViewById(R.id.title5);
		title6		= (TextView)findViewById(R.id.title6);
		title7		= (TextView)findViewById(R.id.title7);
		title8		= (TextView)findViewById(R.id.title8);
		title_tv    = (TextView)findViewById(R.id.detail_tv_title);
		pin_tv     	= (TextView)findViewById(R.id.detail_pin_tv);
		nickname_tv = (TextView)findViewById(R.id.detail_nickname_tv);
		nickname_layout = (RelativeLayout) findViewById(R.id.nickname_layout_id);
		email_layout = (RelativeLayout) findViewById(R.id.email_layout_id);
		mobile_layout = (RelativeLayout) findViewById(R.id.mobile_layout_id);
		birth_layout = (RelativeLayout) findViewById(R.id.birth_layout_id);
		gender_layout = (RelativeLayout) findViewById(R.id.gender_layout_id);
		country_layout = (RelativeLayout) findViewById(R.id.country_layout_id);
		lan_layout = (RelativeLayout) findViewById(R.id.lan_layout_id);
		icon_iv	= (ImageView)findViewById(R.id.icon_iv);
	}

	private void initDatas(){
		imageCrop	= new ImageCrop(ContactDetailsAboutActivity.this);
		tpChat		= ((ApplicationTrans)getApplicationContext()).getTpChat();
		skyid		= getIntent().getIntExtra("skyid", -1);
		if(skyid == -1) return;
		buddyinfo = SkyidOperation.getTpBuddyInfo(this, skyid);
		if(buddyinfo != null){
			setValues();
			return;
		}
		
		tpChat.tp_chat_get_info(skyid, new DataCallBack() {
			
			@Override
			public void Callback(int result, RspData resultdata, Object obj) {
				switch (result) {
				case TpChat.CHAT_GETINFO_ERR:
				case TpChat.CHAT_GETINFO_TIMEOUT:
					handler.sendEmptyMessage(TpChat.CHAT_GETINFO_TIMEOUT);
					break;
				case TpChat.CHAT_GETINFO_OK:
					buddyinfo = (TPBuddyinfo)obj;
					handler.sendEmptyMessage(TpChat.CHAT_GETINFO_OK);
					break;
				}
			}
		});
	}
	
	private void setValues(){
		if(null != buddyinfo){
			title1.setText(buddyinfo.getName());
			title2.setText(buddyinfo.getEmail()); //work@xece.com
	//		title3.setText("home@xece.com"); //home@xece.com
			title4.setText(buddyinfo.getPnum());
			title5.setText(buddyinfo.getBirthday());
			String gender = buddyinfo.getSex() == 1?getString(R.string.male):getString(R.string.female);
			title6.setText(gender);
			title7.setText(buddyinfo.getCountry());
			title8.setText(buddyinfo.getLanstr());
			title_tv.setText(buddyinfo.getAlias());
			pin_tv.setText(this.getString(R.string.pin)+":"+buddyinfo.getSkyid());
			nickname_tv.setText(buddyinfo.getAlias());
			if(null != buddyinfo.getAvatar_fpath() && buddyinfo.getAvatar_fpath().length() > 0){
				
			}else{
				String fileName;
				if(0 == buddyinfo.getAvatarid())
					fileName = "avatarf";
				else
					fileName = "avatar"+(buddyinfo.getAvatarid()-2);//3 is the base id of mtk
				try {
					int resId = R.drawable.class.getDeclaredField(fileName).getInt(R.drawable.class);
					icon_iv.setImageResource(resId);
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SecurityException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NoSuchFieldException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		btn_systemavatar.setVisibility(View.INVISIBLE);
		btn_camera.setVisibility(View.INVISIBLE);
		//判断是否是好友
		if(Globals.skyid == skyid){//本人
			btn_addfrd.setVisibility(View.INVISIBLE);
			btn_chat.setVisibility(View.INVISIBLE);
			btn_systemavatar.setVisibility(View.VISIBLE);
			btn_camera.setVisibility(View.VISIBLE);
		}else if(tpChat.tp_chat_getBuddyinfo(skyid) != null){
			btn_addfrd.setVisibility(View.INVISIBLE);
		}
		
	}
	
	private void clickEvents(){
		btn_chat.setOnClickListener(this);
		btn_sms.setOnClickListener(this);
		btn_addfrd.setOnClickListener(this);
		btn_call.setOnClickListener(this);
		btn_systemavatar.setOnClickListener(this);
		btn_camera.setOnClickListener(this);
		nickname_layout.setOnClickListener(this);
		email_layout.setOnClickListener(this);
		mobile_layout.setOnClickListener(this);
		birth_layout.setOnClickListener(this);
		gender_layout.setOnClickListener(this);
		country_layout.setOnClickListener(this);
		lan_layout.setOnClickListener(this);
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.detail_btn_chat:
			Intent intentChat 	= new Intent();
			Bundle bundle		= new Bundle();
			bundle.putSerializable("tpbuddyinfo", buddyinfo);
			intentChat.putExtras(bundle);
			intentChat.setClass(ContactDetailsAboutActivity.this, ChatConversationActivity.class);
			startActivity(intentChat);
			break;
		case R.id.btn_sms: //发送短信
			Intent intentSms = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:10086"));
			startActivity(intentSms);
			break;
		case R.id.detail_btn_addfrd: //添加好友
			tpChat.tp_chat_add_buddy(BuddyInfoUtil.getAlias(Globals.myInfo), buddyinfo.getSkyid(), tpChat.tp_chat_getfriendsgid(), "");
			btn_addfrd.setEnabled(false);
			break;
		case R.id.btn_call:{
			Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:10086"));
			startActivity(intent);
		}
			break;
		case R.id.detail_systemavatar:{
			Intent intent = new Intent(this, SettingSystemAvatarActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.btn_camera:
			imageCrop.getDialog().show();
//			cameraMethod();
			break;
		case R.id.nickname_layout_id:{
			Intent intent = new Intent(this, SettingNicknameActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.email_layout_id:
		case R.id.mobile_layout_id:
		{
			// TODO Auto-generated method stub
			if(Globals.skyid != skyid)
				return;
			LayoutInflater inflater = getLayoutInflater();
			final int cmd = v.getId();
			final  View layout = inflater.inflate(R.layout.layout_setting_editemail, (ViewGroup) findViewById(R.id.layout_setting_editemail_id));
			AlertDialog show = new AlertDialog.Builder(ContactDetailsAboutActivity.this)
			.setTitle(getResources().getString(R.string.modify))
			.setView(layout).setPositiveButton("Save", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					EditText editText1 = (EditText) layout.findViewById(R.id.set_edit_email);
					String email = editText1.getText().toString().trim();
					if(email.equals("")){
						showToast(getString(R.string.string_isnull));
					}
					else if (cmd==R.id.email_layout_id &&SkyUtil.checkEmail(email)) {
						TPBuddyinfo myinfo = new TPBuddyinfo();
						myinfo.setEmail(email);
						((ApplicationTrans)getApplicationContext()).getTpChat().tp_chat_set_info(myinfo);
						title2.setText(email);
						dialog.dismiss();
					}else if (cmd==R.id.mobile_layout_id &&SkyUtil.checkPhone(email)) {
						TPBuddyinfo myinfo = new TPBuddyinfo();
						myinfo.setPnum(email);
						((ApplicationTrans)getApplicationContext()).getTpChat().tp_chat_set_info(myinfo);
						title4.setText(email);
						dialog.dismiss();
					} else {
						showToast(getString(R.string.emailerr));
					}

				}
			}).show();
		}
			break;
		case R.id.birth_layout_id:
		{
			if(Globals.skyid != skyid)
				return;
			Calendar cal=Calendar.getInstance(); //获取时间用的
			DatePickerDialog date=new DatePickerDialog(this,new DatePickerDialog.OnDateSetListener(){
		         
		         public void onDateSet(DatePicker view,int year,int month,int dat){
						TPBuddyinfo myinfo = new TPBuddyinfo();
						myinfo.setBirthday(year+"/"+month+"/"+dat);//y/m/d server format
						tpChat.tp_chat_set_info(myinfo);
						title5.setText(year+"-"+month+"-"+dat);
						if(null != Globals.myInfo){
							Globals.myInfo.setBirthday(year+"-"+month+"-"+dat);
						}
		         }
		        },cal.get(Calendar.YEAR),cal.get(Calendar.MONTH),cal.get(Calendar.DAY_OF_MONTH));
			date.show();
		}
			break;
		case R.id.gender_layout_id:
		{
			if(Globals.skyid != skyid)
				return;
			int gender = 0;
			if(null != Globals.myInfo)
				gender = Globals.myInfo.getSex()-1;
			AlertDialog show = new AlertDialog.Builder(ContactDetailsAboutActivity.this)
			.setTitle("Gender").setIcon(android.R.drawable.ic_dialog_info)
		    .setSingleChoiceItems(
		    		getResources().getStringArray( R.array.array_set_gender), 
			     gender,
			     new DialogInterface.OnClickListener() {
			      public void onClick(DialogInterface dialog, int which) {
			    	  LogManager.LogShow("ContactDetailsAboutActivity", "iwhich:"+which);
			    	  if(which<0) 
			    		  return;
						TPBuddyinfo myinfo = new TPBuddyinfo();
						myinfo.setSex(which+1);
						if(null != Globals.myInfo)
							Globals.myInfo.setSex(which+1);
						((ApplicationTrans)getApplicationContext()).getTpChat().tp_chat_set_info(myinfo);
						title6.setText(getResources().getStringArray( R.array.array_set_gender)[which]);
			    	  dialog.dismiss();
			      }
			     })
		     .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
				    	  if(which<0) 
				    		  return;
						TPBuddyinfo myinfo = new TPBuddyinfo();
						LogManager.LogShow("ContactDetailsAboutActivity", "iwhich:"+which);
						myinfo.setSex(which+1);
						if(null != Globals.myInfo)
							Globals.myInfo.setSex(which+1);
						((ApplicationTrans)getApplicationContext()).getTpChat().tp_chat_set_info(myinfo);
						title6.setText(getResources().getStringArray( R.array.array_set_gender)[which]);
		            	dialog.dismiss();
		            }
		        })
		     .show();
		}
			break;
		case R.id.lan_layout_id:{
			Intent intent3 = new Intent(ContactDetailsAboutActivity.this,SettingLanguageActivity.class);
			startActivity(intent3);
		}
			break;
		}
	}

	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		try {
			imageCrop.capituredImage(requestCode, resultCode, data, new CropCallBack() {
				
				@Override
				public void Callback(int result, String url, Object obj) {
					// TODO Auto-generated method stub
					LogManager.LogShow("ContactDetailsAboutActivity", "icon url:"+url + "   bitmap:"+obj);
					Bitmap bitmap = (Bitmap)obj;
					icon_iv.setImageBitmap(bitmap);
				}
			});
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

//	private void showToast(String msg){
//    	if(toast == null){
//    		toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT);
////    		toast.setGravity(Gravity.CENTER, 0, 0);
//    	}else{
//    		toast.setText(msg);
//    	}
//    	toast.show();
//    }
//	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		setValues();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	
}
